package com.ruoyi.common.utils;


import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

public class EmailUtil {
    //发件人地址
    public static String senderAddress = "zhangkm791371870@163.com";
    //发件人账户名
    public static String senderAccount = "zhangkm791371870@163.com";
    //发件人账户密码
    public static String senderPassword = "YDTPWuTWuS6LNSGN";
//    public static String senderPassword = "zhangkm548326326";

    public static void main(String[] args) throws Exception {
//        sendMail("邮件抬头","1149545660@qq.com","邮件内容",new ByteArrayInputStream(new ByteArrayOutputStream().toByteArray()));
        sendEmail("1149545660@qq.com", "邮件抬头", "邮件内容", "http://pic53.nipic.com/file/20141115/9448607_175255450000_2.jpg");
    }

    public static void sendEmail(String recipientAddress, String subject, String content, String imgUrl) throws Exception {
        //1、连接邮件服务器的参数配置
        Properties props = new Properties();
        //设置用户的认证方式
        props.setProperty("mail.smtp.auth", "true");
        //设置传输协议
        props.setProperty("mail.transport.protocol", "smtp");
        //设置发件人的SMTP服务器地址
        props.setProperty("mail.smtp.host", "smtp.163.com");
        //端口
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.port", "465");
        //2、创建定义整个应用程序所需的环境信息的 Session 对象
        Session session = Session.getInstance(props);
        //设置调试信息在控制台打印出来
        session.setDebug(true);
        //3、创建邮件的实例对象
        Message msg = getMimeMessage(session, recipientAddress, subject, content, imgUrl);
        //4、根据session对象获取邮件传输对象Transport
        Transport transport = session.getTransport();
        //设置发件人的账户名和密码
        transport.connect(senderAccount, senderPassword);
        //发送邮件，并发送到所有收件人地址，message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
        transport.sendMessage(msg, msg.getAllRecipients());

        //5、关闭邮件连接
        transport.close();
    }

    public static boolean sendMail(String subject, String toMail, String content, InputStream is) {
        boolean isFlag = false;
        try {
            String smtpFromMail = senderAccount;  //发送邮箱的账号
            String pwd = senderPassword; //16位授权码
            int port = 465; //端口
            String host = "smtp.163.com"; //端口

            Properties props = new Properties();
            //端口
            props.put("mail.smtp.ssl.protocols", "TLSv1.2");

            props.put("mail.smtp.starttls.enable", "false");
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            Session session = Session.getDefaultInstance(props);
            session.setDebug(false);

            MimeMessage message = new MimeMessage(session);
            try {
                InternetAddress internetAddress = new InternetAddress();
                internetAddress.setAddress(smtpFromMail);
                internetAddress.setPersonal("主事丫环","utf-8");
                message.setFrom(internetAddress);
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(toMail));
                message.setSubject(subject);
                message.setSubject(subject,"utf-8");

                /*添加正文内容*/
                Multipart multipart = new MimeMultipart();
                BodyPart contentPart = new MimeBodyPart();
                contentPart.setContent(content,"text/html;charset=UTF-8");
                multipart.addBodyPart(contentPart);

                /*添加附件*/
                MimeBodyPart fileBody = new MimeBodyPart();
                DataSource source = new ByteArrayDataSource(is, "application/msexcel");
                fileBody.setDataHandler(new DataHandler(source));
                String fileName  = "qrcode.xls";
                // 中文乱码问题
                fileBody.setFileName(MimeUtility.encodeText(fileName));
                multipart.addBodyPart(fileBody);

                message.setContent(multipart);
                message.setSentDate(new Date());
                message.saveChanges();
                Transport transport = session.getTransport("smtp");

                transport.connect(host, port, smtpFromMail, pwd);
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
                isFlag = true;
            } catch (Exception e) {
                e.printStackTrace();
                isFlag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isFlag;
    }



    /**
     * 获得创建一封邮件的实例对象
     *
     * @param session
     * @return
     * @throws MessagingException
     * @throws AddressException
     */
    public static MimeMessage getMimeMessage(Session session, String recipientAddress, String subject, String content, String imgUrl) throws Exception {
        //1.创建一封邮件的实例对象
        MimeMessage msg = new MimeMessage(session);
        //2.设置发件人地址
        msg.setFrom(new InternetAddress(senderAddress));
        /**
         * 3.设置收件人地址（可以增加多个收件人、抄送、密送），即下面这一行代码书写多行
         * MimeMessage.RecipientType.TO:发送
         * MimeMessage.RecipientType.CC：抄送
         * MimeMessage.RecipientType.BCC：密送
         */
        msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(recipientAddress));
        //4.设置邮件主题
        msg.setSubject(subject, "UTF-8");


        // 6. 创建文本"节点"
        MimeBodyPart text = new MimeBodyPart();
        // 这里添加图片的方式是将整个图片包含到邮件内容中, 实际上也可以以 http 链接的形式添加网络图片
        if(EmptyUtils.isEmpty(imgUrl)){
            text.setContent(content + "<br/>", "text/html;charset=UTF-8");
        }else{
            text.setContent(content + "<br/><img src='"+imgUrl+"'/>", "text/html;charset=UTF-8");
        }


        // 7. （文本+图片）设置 文本 和 图片"节点"的关系（将 文本 和 图片"节点"合成一个混合"节点"）
        MimeMultipart mm_text_image = new MimeMultipart();
        mm_text_image.addBodyPart(text);
//        mm_text_image.addBodyPart(image);
        mm_text_image.setSubType("related");    // 关联关系

        // 8. 将 文本+图片 的混合"节点"封装成一个普通"节点"
        // 最终添加到邮件的 Content 是由多个 BodyPart 组成的 Multipart, 所以我们需要的是 BodyPart,
        // 上面的 mailTestPic 并非 BodyPart, 所有要把 mm_text_image 封装成一个 BodyPart
        MimeBodyPart text_image = new MimeBodyPart();
        text_image.setContent(mm_text_image);


        // 10. 设置（文本+图片）和 附件 的关系（合成一个大的混合"节点" / Multipart ）
        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(text_image);
        mm.setSubType("mixed");         // 混合关系

        // 11. 设置整个邮件的关系（将最终的混合"节点"作为邮件的内容添加到邮件对象）
        msg.setContent(mm);
        //设置邮件的发送时间,默认立即发送
        msg.setSentDate(new Date());

        return msg;
    }

}